package lv.solcraft.replication.client.http;

import java.io.IOException;

import lv.solcraft.replication.common.client.ClientSettings;
import lv.solcraft.replication.common.server.SettingsFacade;
import net.sf.json.JSONObject;

import org.restlet.Client;
import org.restlet.data.Response;
import org.springframework.util.Assert;

import com.noelios.restlet.application.DecodeRepresentation;

public class HttpSettingsFacade implements SettingsFacade {

    private String serverUrl;

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public ClientSettings getClientSettings(String serverName) {
        String url = serverUrl + "/" + serverName + "/config";
        JSONObject json;
        try {
            json = configRequest(url);
        } catch (IOException e) {
            throw new RuntimeException("Error while getting client config via HTTP GET, " + url, e);
        }
        ClientSettings settings = new ClientSettings(json);
        return settings;
    }

    protected JSONObject configRequest(String urlString) throws IOException {
        Client client = HttpClientFactory.get();
        Response response = client.get(urlString);
        try {
            String responseText = response.isEntityAvailable() ? new DecodeRepresentation(response.getEntity())
                    .getText() : null;
            Assert.isTrue(response.getStatus().isSuccess(), "Loading client config request failed with response code: "
                    + response.getStatus().getCode() + ", url " + urlString + ", response " + responseText);
            JSONObject json = JSONObject.fromObject(responseText);
            return json;
        } finally {
            response.release();
        }
    }
}
